<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\VLesson as LessonModel;
use fast\Tree;
use think\Db;

/**
 * 章节信息
 *
 * @icon fa fa-circle-o
 */
class VLesson extends Backend
{

    /**
     * VLesson模型对象
     * @var \app\admin\model\VLesson
     */
    protected $model = null;
    protected $categorylist = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\VLesson;
        $this->view->assign("isFreeList", $this->model->getIsFreeList());

        $tree = Tree::instance();
        $tree->init(collection($this->model->order('sort asc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'title');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }

        $this->view->assign("parentList", $categorydata);
        $typeList = LessonModel::getTypeList();
        $this->view->assign("typeList", $typeList);
    }

    protected $type;

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        $type = $this->request->request("type");
        $this->type = $type;

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //构造父类select列表选项数据
            $list = [];

            $course_ids = array_column($this->categorylist, 'v_course_id');
            $video_ids = array_column($this->categorylist, 'v_video_id');

            $video_list = \app\admin\model\VVideo::getVideo($video_ids);
            $course_list = \app\admin\model\VCourse::getCourse($course_ids);

            foreach ($this->categorylist as $k => &$v) {
                $v['course'] = isset($course_list[$v['v_course_id']]) ? $course_list[$v['v_course_id']] : "";
                $v['video'] = isset($video_list[$v['v_video_id']]) ? $video_list[$v['v_video_id']] : "";

                if ($type == "all" || $type == null) {
                    $list = $this->categorylist;
                } elseif ($v['v_course_id'] == $type) {
                    $list[] = $v;
                }
            }

            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
}
